package ch.nostromo.tiffanys.clients.xboard.controller;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import ch.nostromo.lib.controller.NosController;
import ch.nostromo.lib.controller.NosControllerException;
import ch.nostromo.lib.controller.NosSettingsException;
import ch.nostromo.tiffanys.clients.xboard.xbif.XBoardInterface;

public class XBoardController extends NosController  {

  private static Logger logger = Logger.getLogger(XBoardController.class.getName());

  private static XBoardController instance = null;

  private final static File tiffanysSettingsFile = new File(System.getProperty("user.home") + "/.tiffanys", "xboard-" + uk.ac.cam.cl.projectcharlie2010.Charlies.VERSION + ".xml");

  private XBoardSettings settings = null;

  /**
   * Returns the one and only instance of the controller.
   * 
   * @return The instance value
   */
  public static XBoardController getInstance() {
    if (instance == null) {
      instance = new XBoardController();
    }

    return instance;
  }

  /**
   * Initialize the application (read parameters, start logging etc.)
   * 
   * @param args
   *          Command line arguments
   */
  public void init(String[] args) {
    try {

      // Load client settings (if not found, try to save them for the first
      // time)
      try {
        settings = new XBoardSettings(tiffanysSettingsFile);
      } catch (NosSettingsException err) {
        settings = new XBoardSettings();
        settings.writeSettingsToXml(tiffanysSettingsFile);
        settings = new XBoardSettings(tiffanysSettingsFile);
      }


      this.initController(settings);

      // Start initializing
      logger.info("Starting Tiffanys XBoard Interface " + uk.ac.cam.cl.projectcharlie2010.Charlies.VERSION + ".");

      // Adding shutdown hook for clean exit
      Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
          endApp();
        }
      });

      XBoardInterface xboardInterface = new XBoardInterface();
      xboardInterface.playGame();

    } catch (NosSettingsException e) {
      System.err.println(e);
      logger.log(Level.SEVERE, "Unexpected Exception, program halted !", e);
      endApp();
    } catch (IOException e) {
      System.err.println(e);
      logger.log(Level.SEVERE, "Unexpected Exception, program halted !", e);
      endApp();
    } catch (NosControllerException e) {
      System.err.println(e);
      logger.log(Level.SEVERE, "Unexpected Exception, program halted !", e);
      endApp();
    }

  }

  public void endApp() {
    logger.info("Shutdown Tiffanys.");
  }

  public XBoardSettings getSettings() {
    return settings;
  }

  public void setSettings(XBoardSettings settings) {
    this.settings = settings;
  }

}
